# --*-- coding: utf-8 --*--

"""
cookie等身份认证信息读写
"""

import os
import xlrd
import pandas
import xlwt
import xlutils.copy as cp
from src import Config

DATA_PATH = os.path.join(Config.project_dir, "Data")  # 获取DATA文件路径
cookie_filename = 'Cookies.xls'
cookie_sheetname = 'cookies'
class Cookie(object):

	@staticmethod
	def read_excel_xlrd(book_name, sheet_name):
		# 打开Excel文件，读取excl文件，存储为字典
		wb = xlrd.open_workbook(book_name)
		sheet = wb.sheet_by_name(sheet_name)
		dic = {}
		for i in range(sheet.nrows - 1):
			lis = []
			for j in range(sheet.ncols):
				lis.append(sheet.cell(i + 1, j).value)
			dic[sheet.cell(i + 1, 0).value] = lis
		print("--------->", type(dic), dic)
		return dic

	@staticmethod
	def read_excel(book_name, sheet_name):
		# 打开Excel文件，读取excl文件sheet_name页，存储为字典
		df = pandas.read_excel(book_name, sheet_name, dtype=str)  # 读出来统一为字符串类型
		df.fillna('', inplace=True)  # 替换excel的nan为空字符串
		dic = {}
		for i in df.values:
			lis = list(i)
			dic[lis[0]] = lis
		return dic

	def remove_order(self, num, dic4, dic2):
		flag = False
		sum = 0
		for i in dic4.keys():
			if num == i:  # 判定指定属性，确定删除行
				sum += 1
				dic2.pop(num)
				self.update_excel(dic2, os.path.join(DATA_PATH, cookie_filename), cookie_filename, sum)
				flag = True
				break
		return flag

	@staticmethod
	def find_and_delete(dic1, dic2, string):
		need_del_str = string
		not_need = []

		for i in dic1.keys():

			my_str = str(i)
			r1 = need_del_str in my_str

			if r1:
				not_need.append(i)

		for k in not_need:
			dic2.pop(k)

		return dic2

	@staticmethod
	def update_excel_xlrd(dic, book_name, sheet_name, num=0):
		wb = xlrd.open_workbook(book_name)
		sheet = wb.sheet_by_name(sheet_name)
		new_wb = cp.copy(wb)  # 将原有的Excel，拷贝一个新的副本
		new_sheet = new_wb.get_sheet(0)
		m = 0
		i = 0
		for i in dic.keys():
			m += 1
			n = 0
			for j in dic[i]:
				new_sheet.write(m, n, j if type(j) is str else str(j))
				n += 1
		for h in range(m + 1, m + 1 + num):
			m += 1
			n = 0
			for k in dic[i]:
				new_sheet.write(m, n, '')
				n += 1
		new_wb.save(book_name)

	@staticmethod
	def update_excel(dic, book_name, sheet_name, num=0):
		"""将dic写入excel，表头不变"""
		wb = xlrd.open_workbook(book_name)
		sheet = wb.sheet_by_name(sheet_name)
		new_wb = cp.copy(wb)  # 将原有的Excel，拷贝一个新的副本
		new_sheet = new_wb.get_sheet(0)
		m = 0
		i = 0
		for i in dic.keys():
			m += 1
			n = 0
			for j in dic[i]:
				new_sheet.write(m, n, j if type(j) is str else str(j))
				n += 1
		for h in range(m + 1, m + 1 + num):
			m += 1
			n = 0
			for k in dic[i]:
				new_sheet.write(m, n, '')
				n += 1
		new_wb.save(book_name)

	def cookie_write(self, cookie, authorization, login_name):
		"""
		存储用户登录后的cookie方式，在登录功能中，引入此方法即可
		:param authorization: 用于档案、影像身份认证
		:param cookie: 就是在登录时采用cookies = response.cookies.get_dict()方法获取的内容
		:param login_name: 登录用户的账户信息
		:return: 保存结果值0为通过，-1为失败
		"""
		cookies = cookie
		cookie_key = tuple(cookies.keys())  # 取出key值
		cookie_value = tuple(cookies.values())  # 取出value值
		cookies_key = ''.join(cookie_key)
		cookies_value = ''.join(cookie_value)
		cookies_all = str(cookies_key) + '=' + str(cookies_value)

		read = self.read_excel(os.path.join(DATA_PATH, cookie_filename), cookie_sheetname)

		read[login_name] = [login_name, cookies_all, authorization]
		self.update_excel(read, os.path.join(DATA_PATH, cookie_filename), cookie_sheetname, num=0)

	@staticmethod
	def cookie_read(login_name):
		"""
		后续接口中使用cookie，采用此方法直接获取
		:param login_name: 登录用户的账户信息
		:return: 返回当前用户的cookie值
		"""
		read = __class__().read_excel(os.path.join(DATA_PATH, cookie_filename), cookie_sheetname)
		read_value = read.get(login_name if isinstance(login_name, str) else login_name)
		if not read_value:
			read_value = [login_name, '', '']
		read_dict = {
			"cookie": str(read_value[1]),
			"authorization": str(read_value[2])
		}
		return read_dict


if __name__ == '__main__':
	filepath = os.path.join(DATA_PATH, cookie_filename)
	sheetname = 'cookies'  # update_excel
	dd = Cookie().read_excel(filepath, sheetname)
	dd.get('3333')[0] = '3333'
	Cookie().update_excel(dd, filepath, sheetname)
	dd = Cookie().read_excel(filepath, sheetname)
	print(dd)

